package com.xdjd.mobile.system;

import com.gitee.easyopen.ApiConfig;
import com.gitee.easyopen.Result;
import com.gitee.easyopen.exception.ApiException;
import com.gitee.easyopen.interceptor.ApiInterceptor;
import com.gitee.easyopen.message.Errors;
import com.gitee.easyopen.session.RedisSessionManager;
import com.gitee.easyopen.support.ApiController;
import com.xdjd.mobile.business.constant.ErrorCodeEnum;
import com.xdjd.mobile.business.util.RequestUtil;
import com.xdjd.mobile.system.interceptor.ApiAuthInterceptor;
import com.xdjd.mobile.system.interceptor.ForceUpdateInterceptor;
import com.xdjd.mobile.system.interceptor.LockInterceptor;
import com.xdjd.mobile.system.interceptor.LogInterceptor;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(value = "/api")
public class IndexController extends ApiController implements EnvironmentAware {

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;

    private String springProfilesPctive;

    @Override
    protected void initApiConfig(ApiConfig apiConfig) {
        // 配置秘钥键值对
        Map<String, String> appSecretStore = new HashMap<String, String>();
        appSecretStore.put("ios", "123456");
        appSecretStore.put("android", "123456");
        appSecretStore.put("h5", "123456");

        apiConfig.setInterceptors(new ApiInterceptor[]{new LogInterceptor(), new LockInterceptor(), new ForceUpdateInterceptor()});
        RedisSessionManager sessionManager = new RedisSessionManager(redisTemplate);
        sessionManager.setKeyPrefix("session-xdjd_demo:");
        sessionManager.setSessionTimeout(60 * 1); // 过期时间分钟，1小时
        apiConfig.setSessionManager(sessionManager);
        apiConfig.addAppSecret(appSecretStore);

        if ("dev,test".contains(springProfilesPctive)) {
            apiConfig.setShowDoc(true); // 显示文档页面
        }

        apiConfig.openAppMode();
    }

    @Override
    public Result caugthException(Throwable e) {
        if (e instanceof InvocationTargetException) {
            e = ((InvocationTargetException) e).getTargetException();
        }
        logger.error(e.getMessage(), e);

        String code = Errors.SYS_ERROR.getCode();
        String msg = ErrorCodeEnum.default_error.getDesc();
        Object data = null;

        if (e instanceof ApiException) {
            ApiException apiEx = (ApiException) e;
            if (!apiEx.getCode().equals("-9")) {
                code = apiEx.getCode();
                msg = apiEx.getMessage();
                data = apiEx.getData();
            }
        }
        return this.apiConfig.getResultCreator().createErrorResult(code, msg, data);
    }

    @Override
    public void setEnvironment(Environment environment) {
        springProfilesPctive = environment.getProperty("spring.profiles.active");
    }

    @Override
    public void index(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        RequestUtil.setResponse(response);
        super.index(request, response);
    }

    @Override
    public void processDocVelocityContext(VelocityContext context) {
        context.put("is_expand_all", false);
    }
}
